package org.flint92.springcloud.config.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;

/**
 * @author flint92
 */
@SpringBootApplication
@EnableDiscoveryClient
@Slf4j
public class ConfigClientApplication {

    private final ContextRefresher contextRefresher;

    @Autowired
    public ConfigClientApplication(ContextRefresher contextRefresher) {
        this.contextRefresher = contextRefresher;
    }

    @Scheduled(fixedRate = 1000L)
    public void refresh() {
        Set<String> keys = contextRefresher.refresh();
        if (log.isInfoEnabled()) {
            log.info("本次更新项:" + keys);
        }
    }

    @Bean
    public CustomHealthIndicator customHealthIndicator() {
        return new CustomHealthIndicator();
    }

    private class CustomHealthIndicator implements HealthIndicator {

        @Override
        public Health health() {
            Health.Builder builder = Health.status(Status.UP);

            builder.withDetail("Name", "CustomHealthIndicator");
            builder.withDetail("Timestamp", System.currentTimeMillis());

            return builder.build();
        }
    }


    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication.class, args);
    }

}
